package com.datagateway.controller;

import com.datagateway.component.DataLineageTracker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据血缘控制器
 * 提供数据血缘追踪的API接口
 * 
 * @author Data Gateway Team
 * @version 1.0.0
 */
@RestController
@RequestMapping("/api/lineage")
public class DataLineageController {

    @Autowired
    private DataLineageTracker dataLineageTracker;

    /**
     * 获取数据血缘统计信息
     * 
     * @return 统计信息
     */
    @GetMapping("/statistics")
    public Map<String, Object> getStatistics() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            DataLineageTracker.DataLineageStatistics statistics = dataLineageTracker.getStatistics();
            
            result.put("success", true);
            result.put("statistics", statistics);
            result.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取数据血缘统计信息失败: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }

    /**
     * 查询数据血缘关系
     * 
     * @param dataId 数据ID
     * @return 数据血缘关系
     */
    @GetMapping("/query/{dataId}")
    public Map<String, Object> queryDataLineage(@PathVariable String dataId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            DataLineageTracker.DataLineage lineage = dataLineageTracker.queryDataLineage(dataId);
            
            result.put("success", true);
            result.put("dataId", dataId);
            result.put("lineage", lineage);
            result.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询数据血缘关系失败: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }

    /**
     * 查询数据血缘链路
     * 
     * @param dataId 数据ID
     * @param maxDepth 最大深度
     * @return 数据血缘链路
     */
    @GetMapping("/chain/{dataId}")
    public Map<String, Object> queryDataLineageChain(@PathVariable String dataId, 
                                                    @RequestParam(defaultValue = "10") int maxDepth) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<DataLineageTracker.DataLineage> lineageChain = dataLineageTracker.queryDataLineageChain(dataId, maxDepth);
            
            result.put("success", true);
            result.put("dataId", dataId);
            result.put("maxDepth", maxDepth);
            result.put("lineageChain", lineageChain);
            result.put("chainLength", lineageChain.size());
            result.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询数据血缘链路失败: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }

    /**
     * 查询数据影响分析
     * 
     * @param dataId 数据ID
     * @param maxDepth 最大深度
     * @return 影响的数据列表
     */
    @GetMapping("/impact/{dataId}")
    public Map<String, Object> queryDataImpactAnalysis(@PathVariable String dataId, 
                                                      @RequestParam(defaultValue = "10") int maxDepth) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<DataLineageTracker.DataLineage> impactList = dataLineageTracker.queryDataImpactAnalysis(dataId, maxDepth);
            
            result.put("success", true);
            result.put("dataId", dataId);
            result.put("maxDepth", maxDepth);
            result.put("impactList", impactList);
            result.put("impactCount", impactList.size());
            result.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询数据影响分析失败: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }

    /**
     * 更新数据血缘关系
     * 
     * @param dataId 数据ID
     * @param request 血缘关系更新请求
     * @return 操作结果
     */
    @PutMapping("/update/{dataId}")
    public Map<String, Object> updateDataLineage(@PathVariable String dataId, 
                                                @RequestBody DataLineageUpdateRequest request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 创建新的血缘关系
            DataLineageTracker.SourceInfo sourceInfo = new DataLineageTracker.SourceInfo(
                request.getSourceId(),
                request.getSourceName(),
                request.getPartition(),
                request.getOffset(),
                System.currentTimeMillis()
            );
            
            DataLineageTracker.TransformationInfo transformationInfo = new DataLineageTracker.TransformationInfo(
                request.getTransformationId(),
                request.getTransformationName(),
                request.getDataSize(),
                System.currentTimeMillis()
            );
            
            DataLineageTracker.TargetInfo targetInfo = new DataLineageTracker.TargetInfo(
                request.getTargetId(),
                request.getTargetName(),
                request.getTargetType(),
                System.currentTimeMillis()
            );
            
            DataLineageTracker.DataLineage lineage = new DataLineageTracker.DataLineage(
                dataId,
                sourceInfo,
                transformationInfo,
                targetInfo,
                System.currentTimeMillis()
            );
            
            dataLineageTracker.updateDataLineage(dataId, lineage);
            
            result.put("success", true);
            result.put("dataId", dataId);
            result.put("message", "数据血缘关系更新成功");
            result.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新数据血缘关系失败: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }

    /**
     * 删除数据血缘关系
     * 
     * @param dataId 数据ID
     * @return 操作结果
     */
    @DeleteMapping("/delete/{dataId}")
    public Map<String, Object> deleteDataLineage(@PathVariable String dataId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            dataLineageTracker.deleteDataLineage(dataId);
            
            result.put("success", true);
            result.put("dataId", dataId);
            result.put("message", "数据血缘关系删除成功");
            result.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除数据血缘关系失败: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }

    /**
     * 清理过期的血缘记录
     * 
     * @return 操作结果
     */
    @PostMapping("/cleanup")
    public Map<String, Object> cleanupExpiredLineage() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            dataLineageTracker.cleanupExpiredLineage();
            
            result.put("success", true);
            result.put("message", "过期血缘记录清理完成");
            result.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "清理过期血缘记录失败: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }

    /**
     * 设置血缘追踪配置
     * 
     * @param request 配置请求
     * @return 操作结果
     */
    @PostMapping("/config")
    public Map<String, Object> setLineageTrackingConfig(@RequestBody LineageConfigRequest request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            dataLineageTracker.setLineageTrackingConfig(
                request.isEnabled(),
                request.getMaxDepth(),
                request.getRetentionDays()
            );
            
            result.put("success", true);
            result.put("enabled", request.isEnabled());
            result.put("maxDepth", request.getMaxDepth());
            result.put("retentionDays", request.getRetentionDays());
            result.put("message", "数据血缘追踪配置已更新");
            result.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "设置数据血缘追踪配置失败: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }

    /**
     * 获取数据血缘链路图
     * 
     * @param dataId 数据ID
     * @param maxDepth 最大深度
     * @return 血缘链路图
     */
    @GetMapping("/graph/{dataId}")
    public Map<String, Object> getDataLineageGraph(@PathVariable String dataId, 
                                                  @RequestParam(defaultValue = "5") int maxDepth) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 查询上游链路
            List<DataLineageTracker.DataLineage> upstreamChain = dataLineageTracker.queryDataLineageChain(dataId, maxDepth);
            
            // 查询下游影响
            List<DataLineageTracker.DataLineage> downstreamImpact = dataLineageTracker.queryDataImpactAnalysis(dataId, maxDepth);
            
            // 构建血缘图
            Map<String, Object> graph = new HashMap<>();
            graph.put("dataId", dataId);
            graph.put("upstreamChain", upstreamChain);
            graph.put("downstreamImpact", downstreamImpact);
            graph.put("upstreamCount", upstreamChain.size());
            graph.put("downstreamCount", downstreamImpact.size());
            
            result.put("success", true);
            result.put("graph", graph);
            result.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取数据血缘链路图失败: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }

    /**
     * 批量查询数据血缘关系
     * 
     * @param request 批量查询请求
     * @return 批量查询结果
     */
    @PostMapping("/batch-query")
    public Map<String, Object> batchQueryDataLineage(@RequestBody BatchQueryRequest request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Map<String, DataLineageTracker.DataLineage> batchResults = new HashMap<>();
            
            for (String dataId : request.getDataIds()) {
                DataLineageTracker.DataLineage lineage = dataLineageTracker.queryDataLineage(dataId);
                if (lineage != null) {
                    batchResults.put(dataId, lineage);
                }
            }
            
            result.put("success", true);
            result.put("batchResults", batchResults);
            result.put("queryCount", request.getDataIds().size());
            result.put("resultCount", batchResults.size());
            result.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "批量查询数据血缘关系失败: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }

    /**
     * 数据血缘更新请求类
     */
    public static class DataLineageUpdateRequest {
        private String sourceId;
        private String sourceName;
        private int partition;
        private long offset;
        private String transformationId;
        private String transformationName;
        private long dataSize;
        private String targetId;
        private String targetName;
        private String targetType;

        // Getter和Setter方法
        public String getSourceId() { return sourceId; }
        public void setSourceId(String sourceId) { this.sourceId = sourceId; }
        
        public String getSourceName() { return sourceName; }
        public void setSourceName(String sourceName) { this.sourceName = sourceName; }
        
        public int getPartition() { return partition; }
        public void setPartition(int partition) { this.partition = partition; }
        
        public long getOffset() { return offset; }
        public void setOffset(long offset) { this.offset = offset; }
        
        public String getTransformationId() { return transformationId; }
        public void setTransformationId(String transformationId) { this.transformationId = transformationId; }
        
        public String getTransformationName() { return transformationName; }
        public void setTransformationName(String transformationName) { this.transformationName = transformationName; }
        
        public long getDataSize() { return dataSize; }
        public void setDataSize(long dataSize) { this.dataSize = dataSize; }
        
        public String getTargetId() { return targetId; }
        public void setTargetId(String targetId) { this.targetId = targetId; }
        
        public String getTargetName() { return targetName; }
        public void setTargetName(String targetName) { this.targetName = targetName; }
        
        public String getTargetType() { return targetType; }
        public void setTargetType(String targetType) { this.targetType = targetType; }
    }

    /**
     * 血缘配置请求类
     */
    public static class LineageConfigRequest {
        private boolean enabled = true;
        private int maxDepth = 10;
        private long retentionDays = 30;

        // Getter和Setter方法
        public boolean isEnabled() { return enabled; }
        public void setEnabled(boolean enabled) { this.enabled = enabled; }
        
        public int getMaxDepth() { return maxDepth; }
        public void setMaxDepth(int maxDepth) { this.maxDepth = maxDepth; }
        
        public long getRetentionDays() { return retentionDays; }
        public void setRetentionDays(long retentionDays) { this.retentionDays = retentionDays; }
    }

    /**
     * 批量查询请求类
     */
    public static class BatchQueryRequest {
        private java.util.List<String> dataIds;

        // Getter和Setter方法
        public java.util.List<String> getDataIds() { return dataIds; }
        public void setDataIds(java.util.List<String> dataIds) { this.dataIds = dataIds; }
    }
}
